/**
 * 日期格式化
 */
export function dateFormat(date, format) {
  format = format || 'yyyy-MM-dd hh:mm:ss';
  if (date !== 'Invalid Date') {
    let o = {
      "M+": date.getMonth() + 1, //month
      "d+": date.getDate(), //day
      "h+": date.getHours(), //hour
      "m+": date.getMinutes(), //minute
      "s+": date.getSeconds(), //second
      "q+": Math.floor((date.getMonth() + 3) / 3), //quarter
      "S": date.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (let k in o)
      if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
          RegExp.$1.length === 1 ? o[k] :
            ("00" + o[k]).substr(("" + o[k]).length));
    return format;
  }
  return '';
}

/**
 * 从开始到结束时间的所有时间
 */
export const getAllDates = (startDate, endDate, additionalDay) => {
  additionalDay = additionalDay || 0
  const dates = [];
  const currentDate = new Date(startDate);
  let lastDate = new Date(endDate);
  lastDate.setDate(lastDate.getDate() + additionalDay)

  while (currentDate <= lastDate) {
    const formattedDate = formatDate(currentDate);
    dates.push(formattedDate);
    currentDate.setDate(currentDate.getDate() + 1);
  }
  return dates;
}

/**
 * 获取当前时间
 */
export const getNowTime = () => {
  const currentDate = new Date();
  const hours = currentDate.getHours();
  const minutes = currentDate.getMinutes();
  const seconds = currentDate.getSeconds();
  return `${hours}:${minutes}:${seconds}`
}

/**
 * 获取二个日期相差多少天
 */
export const getDiffDays = (date1, date2) => {
  if (date1 === date2) return 1
  const d1 = new Date(formatDate(date1))
  const d2 = new Date(formatDate(date2))
  const diffMs = Math.abs(d1 - d2)
  return Math.floor(diffMs / (1000 * 60 * 60 * 24) + 1)
}

/**
 * 指定给一个时间对象，增加X分钟时间
 */
export const addMinutes = (date, minutes) => {
  const d = new Date(date)
  d.setMinutes(d.getMinutes() + minutes)
  return d
}

/**
 * 判断二个日期对象大小
 */
export const compareDate = (date1, date2) => {
  const d1 = new Date(formatDatetime(date1))
  const d2 = new Date(formatDatetime(date2))
  return d1.getTime() > d2.getTime()
}